package com.yunbiao.ybbusstopplate.serialport.agreement;

import android.text.TextUtils;
import android.util.Log;
import com.yunbiao.ybbusstopplate.bean.LineSiteBean;
import com.yunbiao.ybbusstopplate.bean.SiteInfoBean;
import com.yunbiao.ybbusstopplate.utils.BytesUtils;
import com.yunbiao.ybbusstopplate.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import kotlin.jvm.internal.ByteSpreadBuilder;

/**
 * 通达协议解析
 */
public class TDPortAgreement extends BaseAgreement {
    private static final String TAG = "TDPortAgreement";

    private static TDPortAgreement tdPortAgreement = null;

    private TDPortAgreement() {
    }

    public static TDPortAgreement getInstance() {
        if (tdPortAgreement == null) {
            tdPortAgreement = new TDPortAgreement();
        }
        return tdPortAgreement;
    }

    private StringBuilder hexString = null;
    private String device = "";

    /**
     * 串口数据解析
     *
     * @param bytes
     */
    public synchronized void analysisData(byte[] bytes) {


        String bytesHex = BytesUtils.bytesToHex(bytes);

        Boolean fiveFiveEndLengthGtOne = false;
        Boolean fiveFiveEndLengthEqOne = false;

        // 长度 大于 2
        // 是否55结尾
        // bb10220206b8dfd0c2c8fd08d3dcc1d6bbaad4b70ccde1cdb7c9bdc5c9b3f6cbf9251555
        // 220206b8dfd0c2c8fd08d3dcc1d6bbaad4b70ccde1cdb7c9bdc5c9b3f6cbf9251555
        // bb10220206b8dfd0c2c8fd08d3dcc1d6bbaad4b70ccde1cdb7c9bdc5c9b3f6cb
        // f9251555

        // 长度 等于 2
        // bb101f02033130320ab3f5cabcd5bed4a4c9e80ad6d5b5e3d5bed4a4c9e8c41055
        // bb101f02033130320ab3f5cabcd5bed4a4c9e80ad6d5b5e3d5bed4a4c9e8c410
        // 55

        Log.d("data", " 长度：" + bytes.length + " 拦截前 55结尾的：" + BytesUtils.bytesToHex(bytes));

        if (bytes == null || bytes.length <= 5) {

                // 55结尾 长度 eq 1
               if ("55".equals(bytesHex)){
                   Log.d("data", " 55结尾长度1：" + bytesHex);
                   fiveFiveEndLengthEqOne = true;
               }else {
                   fiveFiveEndLengthEqOne = false;
                   Log.d("data", " 55结尾长度非1：" + bytesHex);
               }

            // 55结尾  长度 2～5
               int bytesLength = bytes.length;
               if (bytesLength > 1){

                   //末尾字节
                   byte myEnd = bytes[bytes.length - 1];
                   String myEndHex = BytesUtils.byteToHex(myEnd);

                   if ("55".equals(myEndHex)){
                       Log.d("data", " 长度：" + bytes.length + " 拦截了55结尾的：" + BytesUtils.bytesToHex(bytes));
                       fiveFiveEndLengthGtOne = true;
                   }else {
                       fiveFiveEndLengthGtOne = false;
                   }

               }



            // 55结尾的放行
            if (!fiveFiveEndLengthEqOne & !fiveFiveEndLengthGtOne){
                Log.d("data", "非 55结尾长度1的、55结尾长度2～5的、拦截  : " +BytesUtils.bytesToHex(bytes));
                return;
            }

        }


        if (hexString == null) {
            hexString = new StringBuilder();
        }

        /**
         * 第一步
         */
        //起始字节
        byte start = bytes[0];
        String startHex = BytesUtils.byteToHex(start);



        if (!fiveFiveEndLengthEqOne){

            //485转TTL有时候会出现结尾5500的情况，需要把结尾的00去掉之后再校验
            byte[] end1 = BytesUtils.SubByte(bytes,bytes.length - 2,2);
            String endHex2 = BytesUtils.bytesToHex(end1);
            Log.d(TAG, "analysisData: 结尾：" + endHex2);
            if(TextUtils.equals("5500",endHex2)){
                Log.d(TAG, "analysisData: 结尾是5500，截取后解析");
                bytes = BytesUtils.SubByte(bytes,0,bytes.length - 1);
            }

            //末尾字节
            byte end = bytes[bytes.length - 1];
            String endHex = BytesUtils.byteToHex(end);


            //开始
            if ("bb".equals(startHex)) {
                Log.d(TAG, "-----------start---------");
                hexString.delete(0, hexString.length());
                device = BytesUtils.byteToHex(bytes[1]);
            }
            //存储数据
            hexString.append(BytesUtils.bytesToHex(bytes));


            //结束
            if ("55".equals(endHex)) {
                Log.d(TAG, "-----------end---------");
                Log.d(TAG, "--->" + hexString.toString());
                String splitStr = "bb" + device;
                String[] hexArray = hexString.toString().split(splitStr);
                for (String ss : hexArray) {
                    if (ss != null && !"".equals(ss)) {
                        byte[] byteArray = BytesUtils.hexToByteArray(splitStr + ss);
                        chioseAgr(byteArray);
                    }
                }
            }else{
                Log.d("data", "hexString 结尾没有55的: " + hexString);
            }

            Log.d("data", "hexString after: " + hexString);

        }else {

            Log.d("data", " hexString: " + hexString);
            Log.d("data", " 处理解析 55结尾长度 eq 1："  + bytesHex);


            byte[] byteArray = BytesUtils.hexToByteArray(hexString + bytesHex);
            chioseAgr(byteArray);

        }




    }

    private void chioseAgr(byte[] bytes) {
        String cmdHex = BytesUtils.byteToHex(bytes[3]);
        Log.d("data", " cmdHex: " + cmdHex);
        try {
            switch (cmdHex) {
                //广播线路状态
                case "01"://线路状态
                    analyzCurrentSiteInfo(bytes);
                    break;
                //路牌字符
                case "02"://起-终、线路名
                    analysisLineInfo(bytes);
                    break;
                //车内屏字符
                case "03"://字符
                    analysisSiteTip(bytes);
                    break;
                //侧牌站点
                case "11"://站点集合
                    agreeLineSite(bytes);
                    break;
                case "12"://首末班时间
                    analyzSiteTime(bytes);
                    break;
                    //其他类型
                case "04":
                case "05":
                case "08":
                case "10":
                case "13":
                case "14":
                    break;
                default:
//                    if (agreementListener != null) {
//                        agreementListener.agreementFailed();
//                    }
                    break;
            }
        } catch (Exception e) {

            Log.d("data", " chioseAgr exception : " + e.getMessage());

//            if (agreementListener != null) {
//                agreementListener.agreementFailed();
//            }
        }
    }

    /**
     * 首末班时间
     * @param bytes
     */
    private void analyzSiteTime(byte[] bytes){
        int startH = BytesUtils.hex16to10(BytesUtils.byteToHex(bytes[4]));
        int startM = BytesUtils.hex16to10(BytesUtils.byteToHex(bytes[5]));
        int endH = BytesUtils.hex16to10(BytesUtils.byteToHex(bytes[6]));
        int endM = BytesUtils.hex16to10(BytesUtils.byteToHex(bytes[7]));

        String startTime=(startH<10?"0"+startH:startH)+":"+(startM<10?"0"+startM:startM);
        String endTime=(endH<10?"0"+endH:endH)+":"+(endM<10?"0"+endM:endM);

        if (agreementListener!=null){
            agreementListener.onSiteTimeResult(startTime,endTime,"","");
        }

    }

    /**
     * 到站、离站信息
     */
    public void analyzCurrentSiteInfo(byte[] bytes) {
        byte[] subByte = BytesUtils.SubByte(bytes, 4, bytes.length - 7);
        String type = BytesUtils.byteToHex(subByte[7]);
        int siteType = -1;
        try {
            siteType = Integer.parseInt(type);
        } catch (NumberFormatException e) {
//            e.printStackTrace();
        }
        if (siteType == 0 || siteType == 1) {
            String index = BytesUtils.bytesToHex(BytesUtils.SubByte(subByte, 0, 6));
            int siteIndex = Integer.parseInt(index);
            Log.d(TAG, "analyzCurrentSiteInfo: siteType-->" + siteType + ",siteIndex->" + siteIndex);
        }
    }

    /**
     * 线路信息
     *
     * @param bytes
     */
    public void analysisLineInfo(byte[] bytes) {
        Log.d("data","通达协议：" + bytes);
        Log.d("data","通达协议：" + bytes.length);
        StringBuilder builder = new StringBuilder();
        for (int i = 4; i < bytes.length - 3; i++) {
            Integer length = Integer.valueOf(BytesUtils.byteToHex(bytes[i]), 16);
            byte[] nameByteArry = new byte[length];
            for (int j = 0; j < length; j++) {
                i = i + 1;
                nameByteArry[j] = bytes[i];
            }
            String hex = BytesUtils.bytesToHex(nameByteArry);
            String name = StringUtils.hexStringToString(hex);
            builder.append(name + ",");
        }
        Log.d("data","通达协议：builder: " + builder);
        String line = builder.toString();
        line = line.substring(0, line.length() - 1);
        String[] lineInfo = line.split(",");
        Log.d(TAG, "analysisLineInfo------");
        if (agreementListener != null) {
            Log.d(TAG, "analysisLineInfo------agreementListener");
            agreementListener.onLineInfoResult(lineInfo);
        }
    }

    /**
     * 站点提示信息展示
     *
     * @param bytes
     */
    private void analysisSiteTip(byte[] bytes) {
        byte[] subByte = BytesUtils.SubByte(bytes, 4, bytes.length - 7);
//        Log.d(TAG, "analysisSiteTip:截取片段： " + BytesUtils.bytesToHex(subByte));

        byte aByte = subByte[subByte.length - 1];
        String s = BytesUtils.byteToHex(aByte);
//        Log.d(TAG, "analysisSiteTip:时间： " + s);

        Integer time = Integer.valueOf(s, 16);

        byte[] bytes1 = BytesUtils.SubByte(subByte, 0, subByte.length - 1);
        String s1 = BytesUtils.bytesToHex(bytes1);
//        Log.d(TAG, "analysisSiteTip:报站HEX： " + s1);
        String tip = StringUtils.hexStringToString(s1);
//        Log.d(TAG, "analysisSiteTip:报站： " + tip);

        Log.d(TAG, "time-->" + time + ",tip-->" + tip);
        String[] infoArray = tip.split(":");
        if (infoArray.length == 2) {
            Log.d(TAG, "array[0]-->" + infoArray[0] + ",array[1]" + infoArray[1]);
            SiteInfoBean siteInfoBean = new SiteInfoBean();
            if (infoArray[0].contains("到站")) {
                siteInfoBean.setStutas(1);
            } else {
                siteInfoBean.setStutas(0);
            }
            Log.d(TAG, "analysisSiteTip: 111111111");

            siteInfoBean.setShowTime(time);
            siteInfoBean.setSiteName(infoArray[1]);

            Log.d(TAG, "analysisSiteTip: 22222222222222");

            if (agreementListener != null) {
                agreementListener.onSiteTipResult(siteInfoBean);
            }
        }
    }

    /**
     * 站牌列表数据解析
     *
     * @param bytes
     */
//    private ArrayList<LineSiteBean> siteBeanList;
    private ArrayList<String> siteBeanList;

    private void agreeLineSite(byte[] bytes) {
        if (siteBeanList == null) {
            siteBeanList = new ArrayList<>();
        }
        byte num = bytes[4];
        Integer allNum = Integer.valueOf(BytesUtils.byteToHex(num), 16);//总站点数
        Log.d(TAG,"allNum--->" + allNum);
        for (int i = 5; i < bytes.length - 3; i++) {
            Integer index = Integer.valueOf(BytesUtils.byteToHex(bytes[i]), 16);//站序号
            i = i + 1;
            Integer leanth = Integer.valueOf(BytesUtils.byteToHex(bytes[i]), 16);//站名长度
//            Log.d(TAG, "text: allNum->"+allNum+" ,index:"+index);
            byte[] byteName = new byte[leanth];
            for (int j = 0; j < leanth; j++) {
                i = i + 1;
                byteName[j] = bytes[i];
            }
            String name = StringUtils.hexStringToString(BytesUtils.bytesToHex(byteName));
            Log.d(TAG, "text: allNum->"+allNum+" ,index:"+index+" ,name:"+name);
//            siteBeanList.add(new LineSiteBean(index,name));
            siteBeanList.add(name);
            if (allNum == (index + 1)) {
                Log.d(TAG, "公交站点获取完成");
                if (agreementListener != null) {
                    agreementListener.onSiteListResult(siteBeanList);
                    siteBeanList.clear();
                    siteBeanList = null;
                }
            }
        }
    }
}
